package com.ruoyi.circle.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import com.ruoyi.circle.dao.ICircleStatisticsDao;
import com.ruoyi.circle.domain.CircleBasicInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.level.domain.PointsLevelRule;
import com.ruoyi.level.mapper.PointsLevelRuleMapper;
import com.ruoyi.system.domain.UserAdditionalInfo;
import com.ruoyi.system.mapper.UserAdditionalInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.circle.mapper.CircleMemberRelationMapper;
import com.ruoyi.circle.mapper.CircleBasicInfoMapper;
import com.ruoyi.circle.domain.CircleMemberRelation;
import com.ruoyi.circle.service.ICircleMemberRelationService;

/**
 * 圈子成员关系Service业务层处理
 *
 * @author 区嘉盛
 */
@Service
public class CircleMemberRelationServiceImpl implements ICircleMemberRelationService {
    @Autowired
    private CircleMemberRelationMapper circleMemberRelationMapper;

    @Autowired
    private CircleBasicInfoMapper circleBasicInfoMapper;

    @Autowired
    private ICircleStatisticsDao circleStatisticsDao;

    @Autowired
    private UserAdditionalInfoMapper userAdditionalInfoMapper;

    @Autowired
    private PointsLevelRuleMapper pointsLevelRuleMapper;

    /**
     * 查询圈子成员关系
     *
     * @param id 圈子成员关系主键
     * @return 圈子成员关系
     */
    @Override
    public CircleMemberRelation selectCircleMemberRelationById(Long id) {
        return circleMemberRelationMapper.selectCircleMemberRelationById(id);
    }

    /**
     * 查询圈子成员关系列表
     *
     * @param circleMemberRelation 圈子成员关系
     * @return 圈子成员关系
     */
    @Override
    public List<CircleMemberRelation> selectCircleMemberRelationList(CircleMemberRelation circleMemberRelation) {
        return circleMemberRelationMapper.selectCircleMemberRelationList(circleMemberRelation);
    }

    /**
     * 查询圈子成员列表（包含用户信息）
     *
     * @param circleMemberRelation 圈子成员关系
     * @return 圈子成员关系集合
     */
    @Override
    public List<CircleMemberRelation> selectCircleMemberList(CircleMemberRelation circleMemberRelation) {
        List<CircleMemberRelation> memberList = circleMemberRelationMapper.selectCircleMemberList(circleMemberRelation);
        if (memberList != null && !memberList.isEmpty()) {
            for (CircleMemberRelation member : memberList) {
                String userLevel = getUserLevelInCircle(member.getCircleId(), member.getUserId());
                // 更新数据库中的用户等级
                circleMemberRelationMapper.updateUserLevel(member.getCircleId(), member.getUserId(), userLevel);
                member.setUserLevel(userLevel);
            }
        }
        return memberList;
    }

    /**
     * 获取用户在圈子中的等级
     *
     * @param circleId 圈子ID
     * @param userId   用户ID
     * @return 用户等级名称
     */
    @Override
    public String getUserLevelInCircle(Long circleId, Long userId) {
        UserAdditionalInfo userInfo = userAdditionalInfoMapper.selectUserAdditionalInfoByUserId(userId);
        if (userInfo == null || userInfo.getTotalPoints() == null) {
            return "未知等级";
        }
        Long totalPoints = userInfo.getTotalPoints();

        CircleBasicInfo circleInfo = circleBasicInfoMapper.selectCircleBasicInfoById(circleId);
        if (circleInfo == null || circleInfo.getSystemName() == null || circleInfo.getSystemName().isEmpty()) {
            return "未知等级";
        }
        String systemName = circleInfo.getSystemName();

        PointsLevelRule levelRule = new PointsLevelRule();
        levelRule.setSystemName(systemName);
        levelRule.setLevelStatus(1L);
        List<PointsLevelRule> levelRules = pointsLevelRuleMapper.selectPointsLevelRuleList(levelRule);

        if (levelRules == null || levelRules.isEmpty()) {
            return "未知等级";
        }

        for (PointsLevelRule rule : levelRules) {
            if (totalPoints >= rule.getMinPoints() &&
                    (rule.getMaxPoints() == null || totalPoints <= rule.getMaxPoints())) {
                return rule.getLevelName();
            }
        }
        return "未知等级";
    }

    @Override
    public int updateTransferOwner(Long circleId, Long userId, Long orderOwnerId, String newOwnerName, String orderOwnerName) {
        circleMemberRelationMapper.updateTransferOwner(circleId, userId, 3);
        circleMemberRelationMapper.updateTransferOwner(circleId, orderOwnerId, 1);
        CircleBasicInfo circleBasicInfo = new CircleBasicInfo();
        circleBasicInfo.setId(circleId);
        circleBasicInfo.setOwnerUser(newOwnerName);
        circleBasicInfo.setUpdatedBy(orderOwnerName);
        return circleBasicInfoMapper.updateCircleBasicInfo(circleBasicInfo);
    }

    /**
     * 查询用户在圈子中的角色
     *
     * @param circleId 圈子ID
     * @param userId   用户ID
     * @return 成员角色
     */
    @Override
    public Integer selectUserRoleInCircle(Long circleId, Long userId) {
        return circleMemberRelationMapper.selectUserRoleInCircle(circleId, userId);
    }

    /**
     * 查询圈子成员数量
     *
     * @param circleId 圈子ID
     * @return 成员数量
     */
    @Override
    public int selectCircleMemberCount(Long circleId) {
        return circleMemberRelationMapper.selectCircleMemberCount(circleId);
    }

    /**
     * 新增圈子成员关系
     *
     * @param circleMemberRelation 圈子成员关系
     * @return 结果
     */
    @Override
    public int insertCircleMemberRelation(CircleMemberRelation circleMemberRelation) {
        if (circleMemberRelation.getJoinedTime() == null) {
            circleMemberRelation.setJoinedTime(LocalDateTime.now());
        }
        if (circleMemberRelation.getMemberStatus() == null) {
            circleMemberRelation.setMemberStatus(1);
        }
        int rows = circleMemberRelationMapper.insertCircleMemberRelation(circleMemberRelation);
        if (rows > 0) {
            updateCircleMemberCount(circleMemberRelation.getCircleId());
        }
        return rows;
    }

    /**
     * 修改圈子成员关系
     *
     * @param circleMemberRelation 圈子成员关系
     * @return 结果
     */
    @Override
    public int updateCircleMemberRelation(CircleMemberRelation circleMemberRelation) {
        return circleMemberRelationMapper.updateCircleMemberRelation(circleMemberRelation);
    }

    /**
     * 批量删除圈子成员关系
     *
     * @param ids 需要删除的圈子成员关系主键
     * @return 结果
     */
    @Override
    public int deleteCircleMemberRelationByIds(Long[] ids) {
        if (ids.length > 0) {
            Long currentUserId = SecurityUtils.getUserId();
            for (Long id : ids) {
                CircleMemberRelation relation = circleMemberRelationMapper.selectCircleMemberRelationById(id);
                if (relation != null && currentUserId.equals(relation.getUserId())) {
                    throw new ServiceException("不能移除自己");
                }
            }
            CircleMemberRelation relation = circleMemberRelationMapper.selectCircleMemberRelationById(ids[0]);
            if (relation != null) {
                int rows = circleMemberRelationMapper.deleteCircleMemberRelationByIds(ids);
                if (rows > 0) {
                    updateCircleMemberCount(relation.getCircleId());
                }
                return rows;
            }
        }
        return circleMemberRelationMapper.deleteCircleMemberRelationByIds(ids);
    }

    /**
     * 删除圈子成员关系信息
     *
     * @param id 圈子成员关系主键
     * @return 结果
     */
    @Override
    public int deleteCircleMemberRelationById(Long id) {
        CircleMemberRelation relation = circleMemberRelationMapper.selectCircleMemberRelationById(id);
        if (relation != null) {
            Long currentUserId = SecurityUtils.getUserId();
            if (currentUserId.equals(relation.getUserId())) {
                throw new ServiceException("不能移除自己");
            }
            int rows = circleMemberRelationMapper.deleteCircleMemberRelationById(id);
            if (rows > 0) {
                updateCircleMemberCount(relation.getCircleId());
            }
            return rows;
        }
        return circleMemberRelationMapper.deleteCircleMemberRelationById(id);
    }

    /**
     * 添加圈子成员
     *
     * @param circleId   圈子ID
     * @param userId     用户ID
     * @param memberRole 成员角色
     * @return 结果
     */
    @Override
    public int addCircleMember(Long circleId, Long userId, Integer memberRole) {
        if (checkUserInBlacklist(circleId, userId)) {
            throw new ServiceException("该用户已被加入黑名单，无法添加");
        }
        
        // 检查用户是否已经是圈子活跃成员（状态为1）
        int activeCount = circleMemberRelationMapper.checkUserIsActiveMember(circleId, userId);
        if (activeCount > 0) {
            throw new ServiceException("该成员已在圈子");
        }
        
        int count = circleMemberRelationMapper.checkUserIsCircleMember(circleId, userId);
        if (count > 0) {
            int rows = circleMemberRelationMapper.updateMemberStatus(circleId, userId, 1);
            if (rows > 0) {
                // 更新成员状态后也需要更新圈子成员数量
                updateCircleMemberCount(circleId);
            }
            return rows;
        } else {
            CircleMemberRelation relation = new CircleMemberRelation();
            relation.setCircleId(circleId);
            relation.setUserId(userId);
            relation.setMemberRole(memberRole);
            relation.setMemberStatus(1);
            relation.setBlacklistStatus(0);
            relation.setJoinedTime(LocalDateTime.now());
            int rows = circleMemberRelationMapper.insertCircleMemberRelation(relation);
            if (rows > 0) {
                updateCircleMemberCount(circleId);
            }
            return rows;
        }
    }

    /**
     * 移除圈子成员
     *
     * @param circleId 圈子ID
     * @param userId   用户ID
     * @return 结果
     */
    @Override
    public int removeCircleMember(Long circleId, Long userId) {
        Long currentUserId = SecurityUtils.getUserId();
        if (currentUserId.equals(userId)) {
            throw new ServiceException("不能移除自己");
        }
        int rows = circleMemberRelationMapper.updateMemberStatus(circleId, userId, 2);
        if (rows > 0) {
            updateCircleMemberCount(circleId);
        }
        return rows;
    }

    /**
     * 更新圈子成员角色
     *
     * @param circleId   圈子ID
     * @param userId     用户ID
     * @param memberRole 成员角色
     * @return 结果
     */
    @Override
    public int updateMemberRole(Long circleId, Long userId, Integer memberRole) {
        Long currentUserId = SecurityUtils.getUserId();
        if (currentUserId.equals(userId)) {
            throw new ServiceException("不能修改自己的角色");
        }
        if (memberRole != null && memberRole == 3) {
            CircleMemberRelation param = new CircleMemberRelation();
            param.setCircleId(circleId);
            param.setMemberRole(3);
            param.setMemberStatus(1);
            List<CircleMemberRelation> ownerList = circleMemberRelationMapper.selectCircleMemberRelationList(param);
            for (CircleMemberRelation owner : ownerList) {
                if (!owner.getUserId().equals(userId)) {
                    circleMemberRelationMapper.updateMemberRole(circleId, owner.getUserId(), 1);
                }
            }
        }
        return circleMemberRelationMapper.updateMemberRole(circleId, userId, memberRole);
    }

    /**
     * 更新圈子成员数量
     *
     * @param circleId 圈子ID
     */
    private void updateCircleMemberCount(Long circleId) {
        int memberCount = circleMemberRelationMapper.selectCircleMemberCount(circleId);
        circleBasicInfoMapper.updateCircleMemberCount(circleId, memberCount);
        circleStatisticsDao.updateCircleHeatScore(circleId);
    }

    /**
     * 设置用户黑名单状态
     *
     * @param circleId        圈子ID
     * @param userId          用户ID
     * @param blacklistStatus 黑名单状态（0-正常 1-黑名单）
     * @return 结果
     */
    @Override
    public int updateBlacklistStatus(Long circleId, Long userId, Integer blacklistStatus) {
        Long currentUserId = SecurityUtils.getUserId();
        Integer currentUserRole = circleMemberRelationMapper.selectUserRoleInCircle(circleId, currentUserId);
        if (currentUserRole == null || (currentUserRole != 2 && currentUserRole != 3)) {
            throw new ServiceException("您没有权限执行此操作");
        }
        Integer targetUserRole = circleMemberRelationMapper.selectUserRoleInCircle(circleId, userId);
        if (currentUserRole == 3 && targetUserRole != 1) {
            throw new ServiceException("圈主只能设置普通会员为黑名单");
        }
        if (currentUserId.equals(userId)) {
            throw new ServiceException("不能设置自己为黑名单");
        }
        if (blacklistStatus == 1) {
            circleMemberRelationMapper.updateMemberStatus(circleId, userId, 2);
            updateCircleMemberCount(circleId);
        }
        return circleMemberRelationMapper.updateBlacklistStatus(circleId, userId, blacklistStatus);
    }

    /**
     * 检查用户是否在圈子黑名单中
     *
     * @param circleId 圈子ID
     * @param userId   用户ID
     * @return 是否在黑名单中
     */
    @Override
    public boolean checkUserInBlacklist(Long circleId, Long userId) {
        return circleMemberRelationMapper.checkUserInBlacklist(circleId, userId) > 0;
    }

    /**
     * 普通用户加入圈子
     *
     * @param circleId 圈子ID
     * @param userId   用户ID
     * @return 结果
     */
    @Override
    public int joinCircle(Long circleId, Long userId) {
        if (checkUserInBlacklist(circleId, userId)) {
            throw new ServiceException("您已被加入黑名单，无法加入该圈子");
        }
        int count = circleMemberRelationMapper.checkUserIsCircleMember(circleId, userId);
        if (count > 0) {
            Integer currentRole = circleMemberRelationMapper.selectUserRoleInCircle(circleId, userId);
            if (currentRole != null) {
                throw new ServiceException("您已经是该圈子的成员");
            } else {
                int row = circleMemberRelationMapper.updateMemberStatus(circleId, userId, 1);
                if (row > 0) updateCircleMemberCount(circleId);
                return row;
            }
        } else {
            CircleMemberRelation relation = new CircleMemberRelation();
            relation.setCircleId(circleId);
            relation.setUserId(userId);
            relation.setMemberRole(1);
            relation.setMemberStatus(1);
            relation.setBlacklistStatus(0);
            relation.setJoinedTime(LocalDateTime.now());
            int rows = circleMemberRelationMapper.insertCircleMemberRelation(relation);
            if (rows > 0) {
                updateCircleMemberCount(circleId);
            }
            return rows;
        }
    }

    /**
     * 普通用户退出圈子
     *
     * @param circleId 圈子ID
     * @param userId   用户ID
     * @return 结果
     */
    @Override
    public int leaveCircle(Long circleId, Long userId) {
        Integer memberRole = circleMemberRelationMapper.selectUserRoleInCircle(circleId, userId);
        if (memberRole == null) {
            throw new ServiceException("您不是该圈子的成员");
        }
        if (memberRole == 3) {
            throw new ServiceException("圈主不能退出自己的圈子");
        }
        int rows = circleMemberRelationMapper.updateMemberStatus(circleId, userId, 2);
        if (rows > 0) {
            updateCircleMemberCount(circleId);
        }
        return rows;
    }
}